import 'package:cunyutech_flutter_ui/src/text/main.dart';
import 'package:cunyutech_flutter_ui/src/theme/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'FloatingIndex.dart';
import 'SectionListView.dart';

typedef ContactTapCallback(dynamic item);


class Contact extends StatefulWidget {
  Contact({Key key, @required this.data, @required this.indexData, this.onTap, this.renderItem, this.itemHeight }) : super(key: key);

  final List<SectionItemList> data;
  final List<String> indexData;
  final ContactTapCallback onTap;
  final SectionItemBuilder renderItem;
  final double itemHeight;

  _ContactState createState() => _ContactState();
}

class _ContactState extends State<Contact> {

  ScrollController controller;
  static double defaultItemHeight = 46;
  double headerHeight = 30;
  double itemHeight = 46;

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
    itemHeight = widget.itemHeight ?? defaultItemHeight;
  }

  onActivedHeader(int index) {
    int sum = 0;
    widget.data.sublist(0, index).forEach((list){
      sum += list.list.length;
    });
    double dy = index * headerHeight + sum * itemHeight;
    controller.animateTo(
      dy,
      duration: Duration(milliseconds: 100),
      curve: Curves.easeIn,
    );
  }

  @override
  Widget build(BuildContext context) {
    var cs = CYThemeData.of(context);
    var sectionListView = SectionListView(
      data: widget.data, 
      controller: controller,
      renderSectionItem: (BuildContext context, dynamic item, int itemIndex, SectionItemList itemList) {
        return Container(
          child: InkWell(
            onTap: (){
              if(widget.onTap != null) {
                widget.onTap(item);
              }
            },
            child: widget.renderItem(context, item, itemIndex, itemList),
          )
        );
      }, 
      renderSectionHeader: (BuildContext context, SectionItemList item, int sectionIndex, {double shrinkOffset, bool overlapsContent}) {
        return CYParagraph(
          item.title,
          margin: EdgeInsets.symmetric(horizontal: CYMargin.Default),
          fontSize: CYFontSize.Large,
          width: CYHeight.Default,
        );
      },
    );
    return Stack(
       children: <Widget>[
        sectionListView,
        Container(
          alignment: Alignment.centerRight,
          child: FloatingIndex(
            data: widget.indexData,
            renderItem: (BuildContext context, String item, int itemIndex) {
              return CYParagraph(item, color: cs.foreColorSystem.secondaryColor, alignment: Alignment.center, fontSize: CYFontSize.Large,);
            },
            onTap: (String activedString, int index) {
              onActivedHeader(index);
            },
          ),
        ),
       ],
    );
  }
}